﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using Uber.Storage;

namespace Uber.HabboHotel.Advertisements
{
    class AdvertisementManager
    {
        public List<RoomAdvertisement> RoomAdvertisements;

        private readonly Object _lock;

        public AdvertisementManager()
        {
            this.RoomAdvertisements = new List<RoomAdvertisement>();
            this._lock = new Object();
        }

        public void LoadRoomAdvertisements()
        {
            this.RoomAdvertisements = null;
            this.RoomAdvertisements = new List<RoomAdvertisement>();
            
            DataTable Data = null;

            using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
            {
                Data = dbClient.ReadDataTable("SELECT * FROM room_ads WHERE enabled = '1'");
            }

            if (Data == null)
            {
                return;
            }

            foreach (DataRow Row in Data.Rows)
            {
                RoomAdvertisements.Add(new RoomAdvertisement(Convert.ToUInt32(Row["id"]), Convert.ToString(Row["ad_image"]),
                    Convert.ToString(Row["ad_link"]), Convert.ToInt32(Row["views"]), Convert.ToInt32(Row["views_limit"])));
            }
        }

        public RoomAdvertisement GetRandomRoomAdvertisement()
        {
            if (RoomAdvertisements.Count <= 0)
            {
                return null;
            }

            lock (_lock)
            {
                int RndId = UberEnvironment.GetRandomNumber(0, RoomAdvertisements.Count);

                if (RoomAdvertisements[RndId] != null && !RoomAdvertisements[RndId].ExceededLimit)
                {
                    return RoomAdvertisements[RndId];
                }
            }

            return null;
        }
    }
}
